package com.scau.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.scau.dao.BaseDao;
import com.scau.dao.IProductDao;
import com.scau.vo.Product;

/**
 * @author Jinglun
 * @create 2017年4月18日
 */
public class ProductDaoImpl extends BaseDao implements IProductDao {

	private Session session = null;
	private Transaction tx = null;
	private String hql = "";
	
	@Override
	public boolean saveProduct(Product product) {
		session = getSession();
		tx = session.beginTransaction();
		
		hql = "from Product p where p.name = '" + product.getName() + "'";
		Product exist = (Product) session.createQuery(hql).uniqueResult();
		
		if (exist != null) { // 已存在
			tx.commit();
			session.close(); 
			return false;
		} else { // db中没有记录，可插入
			session.save(product);
			tx.commit(); // 事务关闭数据才真正插入数据库
			session.close(); // 关闭会话，释放资源
			return true;
		}
	}

	@Override
	public boolean deleteProduct(int id) {
		session = getSession();
		tx = session.beginTransaction();
		
		Product product = (Product) session.get(Product.class, id);
		session.delete(product);
		tx.commit();
		session.close();
		return true;
	}

	@Override
	public List<Product> listProduct() {
		session = getSession();
		
		hql = "from Product p";
		Query query = session.createQuery(hql);
		List<Product> productList = query.list();
		session.close();
		return productList;
	}

	@Override
	public boolean updateProduct(Product product) {
		session = getSession();
		tx = session.beginTransaction();
		
		Product pro = (Product) session.get(Product.class, product.getId());
		
		pro.setName(product.getName());
		pro.setPrice(product.getPrice());
		pro.setBrand(product.getBrand());
		pro.setCategory(product.getCategory());
		pro.setRemark(product.getRemark());
		pro.setGmtModified(product.getGmtModified());
		
		tx.commit();
		session.close();
		return true;
	}

}
